import gulp from 'gulp';
import GulpSSH from 'gulp-ssh';
import dotenv from 'dotenv';
import fs from 'fs';
import path from 'path';
// 也可以是 import fs from "fs"; 区别是同步和异步
import { serviceConfigObj } from './appConfig/serviceConfig.mjs';
const currentSetting = {
  // eslint-disable-next-line no-undef
  // eslint-disable-next-line no-undef
  NODE_ENV: process.env.NODE_ENV,
  ...serviceConfigObj,
};
// eslint-disable-next-line no-undef
const gulpSSH = new GulpSSH({
  ignoreErrors: false,
  sshConfig: {
    host: currentSetting.HOST,
    port: currentSetting.PORT,
    username: currentSetting.USERNAME,
    password: currentSetting.PASSWORD,
  },
});
function loadEnvDevelopmentAsObject() {
  const filePath = path.resolve(process.cwd(), `./appConfig/env/.env.${currentSetting.NODE_ENV}`);
  if (!fs.existsSync(filePath)) {
    console.error('.env.development file does not exist');
    return {};
  }
  const result = dotenv.parse(fs.readFileSync(filePath));
  return result;
}

// pm2会保留最初启动应用时的环境变量
function getEnvKeyString() {
  let commands = '';
  let envVariable = [
    'SERVICE_HOST',
    'DB_TYPE',
    'DB_HOST',
    'DB_PORT',
    'DB_USERNAME',
    'DB_PASSWORD',
    'DB_DATABASE',
    'DB_SYNCHRONIZE',
    'COS_SECRETID',
    'COS_SECRETKEY',
    'COS_REGION',
    'COS_BUCKET',
    'COS_URL',
    'SMS_SECRETID',
    'SMS_SECRETKEY',
    'SMS_TEMPLATEID',
    'SMS_SIGNNAME',
    'SMS_SMSSDKAPPID',
    'SMS_REGION',
    'APP_PORT',
    'APP_URL',
    'APP_URL',
    'SWAGGER_TITLE',
    'SWAGGER_DESCRIPTION',
    'SWAGGER_URL',
    'SWAGGER_TITLE_TWO',
    'SWAGGER_DESCRIPTION_TWO',
    'SWAGGER_URL_TWO',
    'EMAIL_SECRET_ID',
    'EMAIL_SECRET_KEY',
    'EMAIL_FROMEMAILADDRESS',
    'EMAIL_TEMPLATEID',
    'ALIPAY_PRIVATEKEY',
    'ALIPAY_PUBLICKEY',
    'ALIPAY_APPID',
    'ALIPAY_CALLBACK',
    'WXPUBLIC_APPID',
    'WXPUBLIC_APPSECRET',
  ];
  const envObject = loadEnvDevelopmentAsObject();
  envVariable.map((envKey) => {
    commands += `export ${envKey}='${envObject[envKey]}'; `;
  });
  console.log(commands);
  return;
}

function firstStartFn() {
  let commands = getEnvKeyString();
  return gulpSSH.shell(commands);
}
gulp.task('testSsh', function () {
  return gulpSSH.exec(['ls -l /'], { filePath: 'files.txt' }).pipe(gulp.dest('logs'));
});

gulp.task('getEnvKeyString', getEnvKeyString);

gulp.task(
  'firstStart',
  gulp.series(
    () => gulp.src(`./dist/**`).pipe(gulpSSH.dest(currentSetting.SERVICE_URL)),
    firstStartFn,
    () => gulpSSH.shell(`pm2 start ${currentSetting.startUpFilePath} --name ${currentSetting.pm2Name}`),
  ),
);

// 当从任务（task）中返回 stream、promise、event emitter、child process 或 observable 时，成功或错误值将通知 gulp 是否继续执行或结束。如果任务（task）出错，gulp 将立即结束执行并显示该错误。
gulp.task(
  'deploy',
  gulp.series(
    () => gulp.src(`./dist/**`).pipe(gulpSSH.dest(currentSetting.SERVICE_URL)),
    () => gulpSSH.shell(`pm2 restart ${currentSetting.pm2Name}`),
  ),
);

gulp.task('start', () => gulpSSH.shell(`pm2 restart ${currentSetting.pm2Name}`));

gulp.task('stop', () => gulpSSH.shell(`pm2 stop ${currentSetting.pm2Name}`));
